<template>
    <div class="blog-detail">
      <!-- 返回按钮 -->
      <div class="back-button" @click="goBack">
        <i class="el-icon-arrow-left"></i>
        <span>返回列表</span>
      </div>
  
      <!-- 文章封面区域 -->
      <div class="article-header" :style="{ backgroundImage: `url(${article.coverUrl})` }">
        <div class="header-overlay">
          <div class="header-content">
            <h1 class="title">{{ article.title }}</h1>
            <div class="meta-info">
              <!-- 作者信息 -->
              <div class="author-info">
                <el-avatar :size="50" :src="getAuthorAvatar">
                  {{ getAuthorFirstLetter }}
                </el-avatar>
                <div class="author-detail">
                  <span class="author-name">{{ getAuthorName }}</span>
                  <div class="publish-info">
                    <i class="el-icon-time"></i>
                    <span>{{ formatDate(article.publishedAt) }}</span>
                    <span class="dot">·</span>
                    <span>{{ article.categoryName }}</span>
                  </div>
                </div>
              </div>
              
              <!-- 文章统计 -->
              <div class="article-stats">
                <div class="stat-item" v-tooltip="'阅读数'">
                  <i class="el-icon-view"></i>
                  <span>{{ article.viewCount || 0 }}</span>
                </div>
                <div class="stat-item" v-tooltip="'点赞数'">
                  <i class="el-icon-star-off"></i>
                  <span>{{ article.likeCount || 0 }}</span>
                </div>
                <div class="stat-item" v-tooltip="'评论数'">
                  <i class="el-icon-chat-dot-round"></i>
                  <span>{{ article.commentCount || 0 }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
  
      <!-- 文章内容区 -->
      <div class="article-container">
        <div class="article-main">
          <!-- 文章标签 -->
          <div class="article-tags">
            <el-tag 
              type="success" 
              effect="dark"
              size="medium">
              {{ article.categoryName }}
            </el-tag>
            <el-tag 
              v-for="tag in article.tags" 
              :key="tag.id"
              type="info"
              effect="plain"
              size="medium"
              class="tag-item">
              {{ tag.name }}
            </el-tag>
          </div>
  
          <!-- Markdown 内容 -->
          <div class="article-content markdown-body">
            <ArticleContent 
              :title="article.title"
              :content="article.content"
              :author="article.author"
              :publishedAt="article.publishedAt"
              :viewCount="article.viewCount"
              :likeCount="article.likeCount"
              :commentCount="article.commentCount"
            />
          </div>
  
          <!-- 文章底部 -->
          <div class="article-footer">
            <div class="keywords" v-if="article.metaKeywords">
              <i class="el-icon-collection-tag"></i>
              <span>关键词：</span>
              <el-tag 
                v-for="keyword in keywords" 
                :key="keyword"
                size="small"
                effect="plain"
                class="keyword-tag">
                {{ keyword }}
              </el-tag>
            </div>
          </div>
        </div>
  
        <!-- 侧边栏 -->
        <div class="article-sidebar">
          <div class="action-card">
            <div class="like-button" 
                 @click="handleLike"
                 :class="{ 'is-liked': isLiked }"
                 v-loading="likeLoading">
              <i :class="isLiked ? 'el-icon-star-on' : 'el-icon-star-off'"></i>
              <span>{{ isLiked ? '已点赞' : '点赞' }}</span>
            </div>
            <div class="share-button" @click="handleShare">
              <i class="el-icon-share"></i>
              <span>分享</span>
            </div>
            <!-- 作者信息卡片 -->
            <div class="author-card">
              <div class="author-header">
                <el-avatar :size="60" :src="getAuthorAvatar">
                  {{ getAuthorFirstLetter }}
                </el-avatar>
                <h3>{{ getAuthorName }}</h3>
              </div>
              <div class="author-bio" v-if="article.author.bio">
                {{ article.author.bio }}
              </div>
              <div class="author-links">
                <a v-if="article.author.githubUrl" 
                   :href="article.author.githubUrl" 
                   target="_blank"
                   class="social-link">
                  <i class="fab fa-github"></i>
                </a>
                <a v-if="article.author.websiteUrl" 
                   :href="article.author.websiteUrl" 
                   target="_blank"
                   class="social-link">
                  <i class="fas fa-globe"></i>
                </a>
              </div>
            </div>
          </div>
        </div>
      </div>
  
      <!-- 分享对话框 -->
      <el-dialog
        title="分享文章"
        :visible.sync="shareDialogVisible"
        width="300px"
        center>
        <div class="share-options">
          <div class="share-item" @click="shareToWeixin">
            <i class="fab fa-weixin"></i>
            <span>微信</span>
          </div>
          <div class="share-item" @click="shareToWeibo">
            <i class="fab fa-weibo"></i>
            <span>微博</span>
          </div>
          <div class="share-item" @click="copyLink">
            <i class="el-icon-link"></i>
            <span>复制链接</span>
          </div>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import axios from 'axios'
  import { Message } from 'element-ui'
  import ArticleContent from './common/ArticleContent.vue'
  
  export default {
    name: 'BlogDetail',
    components: {
      ArticleContent
    },
    data() {
      return {
        article: {
          author: {},
          content: '',
        },
        loading: true,
        isLiked: false,
        likeLoading: false,
        shareDialogVisible: false,
        relatedArticles: [],
        tocHtml: ''
      }
    },
    computed: {
      // 获取作者头像
      getAuthorAvatar() {
        return this.article.author && this.article.author.avatarUrl || ''
      },
      // 获取作者名字首字母
      getAuthorFirstLetter() {
        const nickname = this.article.author && this.article.author.nickname
        return nickname ? nickname.charAt(0) : ''
      },
      // 获取作者名字
      getAuthorName() {
        return this.article.author && this.article.author.nickname || '匿名用户'
      },
      keywords() {
        return this.article.metaKeywords ? this.article.metaKeywords.split(',') : []
      }
    },
    async created() {
      await this.fetchArticle()
      this.generateToc()
    },
    methods: {
      async fetchArticle() {
        try {
          this.loading = true
          const { id } = this.$route.params
          const response = await axios.get(`/api/blog/articles/${id}`)
          if (response.data.code === 200) {
            this.article = response.data.data
            // 打印内容长度，用于调试
            console.log('文章内容长度:', this.article.content.length)
            console.log('文章内容前100个字符:', this.article.content.substring(0, 100))
            // 确保 author 对象存在
            if (!this.article.author) {
              this.article.author = {}
            }
            this.fetchRelatedArticles()
          }
        } catch (error) {
          Message.error('获取文章详情失败')
          console.error('获取文章详情错误:', error)
        } finally {
          this.loading = false
        }
      },
      formatDate(date) {
        if (!date) return ''
        const d = new Date(date)
        return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
      },
      goBack() {
        this.$router.go(-1)
      },
      async handleLike() {
        if (this.likeLoading) return
        this.likeLoading = true
        try {
          // 这里添加点赞 API 调用
          await new Promise(resolve => setTimeout(resolve, 500)) // 模拟 API 调用
          this.isLiked = !this.isLiked
          this.article.likeCount += this.isLiked ? 1 : -1
          Message.success(this.isLiked ? '点赞成功' : '已取消点赞')
        } catch (error) {
          Message.error('操作失败，请稍后重试')
        } finally {
          this.likeLoading = false
        }
      },
      handleShare() {
        this.shareDialogVisible = true
      },
      shareToWeixin() {
        // 实现微信分享逻辑
        this.shareDialogVisible = false
      },
      shareToWeibo() {
        // 实现微博分享逻辑
        this.shareDialogVisible = false
      },
      async copyLink() {
        try {
          await navigator.clipboard.writeText(window.location.href)
          Message.success('链接已复制到剪贴板')
        } catch (err) {
          Message.error('复制失败，请手动复制')
        }
        this.shareDialogVisible = false
      },
      async fetchRelatedArticles() {
        try {
          // 获取相关文章
          const response = await axios.get(`/api/articles/related/${this.article.id}`)
          this.relatedArticles = response.data.slice(0, 5) // 只显示5篇相关文章
        } catch (error) {
          console.error('获取相关文章失败:', error)
        }
      },
      generateToc() {
        const headings = this.article.content.match(/#{2,3}\s[^\n]+/g) || []
        const toc = headings.map(heading => {
          const level = (heading.match(/#/g) || []).length - 1
          const title = heading.replace(/#{2,3}\s/, '')
          const anchor = this.slugify(title)
          return { level, title, anchor }
        })

        this.tocHtml = toc.map(item => 
          `<div class="toc-item level-${item.level}">
            <a href="#${item.anchor}">${item.title}</a>
          </div>`
        ).join('')
      },
      slugify(text) {
        return text.toLowerCase()
          .replace(/\s+/g, '-')
          .replace(/[^\w\-]+/g, '')
          .replace(/\-\-+/g, '-')
          .replace(/^-+/, '')
          .replace(/-+$/, '')
      }
    }
  }
  </script>
  
  <style scoped>
  .blog-detail {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
  }
  
  .back-button {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 8px 16px;
    margin-bottom: 20px;
    background: #fff;
    border-radius: 20px;
    cursor: pointer;
    transition: all 0.3s;
    box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  }
  
  .back-button:hover {
    transform: translateX(-5px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
  }
  
  .article-header {
    height: 500px;
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    border-radius: 12px;
    overflow: hidden;
    position: relative;
  }
  
  .header-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(to bottom, rgba(0,0,0,0.3), rgba(0,0,0,0.7));
    display: flex;
    align-items: flex-end;
    padding: 40px;
  }
  
  .header-content {
    color: #fff;
    width: 100%;
  }
  
  .title {
    font-size: 36px;
    font-weight: bold;
    margin: 0 0 20px 0;
    text-shadow: 0 2px 4px rgba(0,0,0,0.3);
  }
  
  .meta-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .author-info {
    display: flex;
    align-items: center;
    gap: 12px;
  }
  
  .author-detail {
    display: flex;
    flex-direction: column;
  }
  
  .author-name {
    font-size: 16px;
    font-weight: 500;
    color: #303133;
  }
  
  .publish-info {
    font-size: 14px;
    color: #909399;
  }
  
  .dot {
    margin: 0 8px;
  }
  
  .article-stats {
    display: flex;
    gap: 20px;
  }
  
  .stat-item {
    display: flex;
    align-items: center;
    gap: 4px;
    color: #606266;
  }
  
  .article-container {
    display: flex;
    gap: 20px;
  }
  
  .article-main {
    flex: 1;
    background: #fff;
    padding: 30px;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  }
  
  .article-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    margin: 20px 0;
  }
  
  .tag-item {
    transition: all 0.3s;
  }
  
  .tag-item:hover {
    transform: translateY(-2px);
  }
  
  .article-content {
    font-size: 16px;
    line-height: 1.8;
    color: #303133;
  }
  
  .article-footer {
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid #eee;
  }
  
  .keywords {
    display: flex;
    align-items: center;
    gap: 10px;
  }
  
  .keyword-tag {
    margin-right: 8px;
  }
  
  .article-sidebar {
    width: 240px;
  }
  
  .action-card {
    position: sticky;
    top: 20px;
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  }
  
  .like-button,
  .share-button {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    padding: 12px;
    margin-bottom: 10px;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s;
  }
  
  .like-button {
    background: linear-gradient(135deg, #FF6B6B, #FF8E8E);
  }
  
  .like-button.is-liked {
    background: linear-gradient(135deg, #FF4B4B, #FF6E6E);
  }
  
  .share-button {
    background: linear-gradient(135deg, #4CAF50, #45B649);
  }
  
  .like-button:hover,
  .share-button:hover {
    opacity: 0.8;
  }
  
  .author-card {
    margin-top: 20px;
    padding: 20px;
    border-top: 1px solid #eee;
  }
  
  .author-header {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;
  }
  
  .author-bio {
    margin: 15px 0;
    color: #606266;
    text-align: center;
    font-size: 14px;
  }
  
  .author-links {
    display: flex;
    justify-content: center;
    gap: 15px;
  }
  
  .social-link {
    color: #606266;
    font-size: 20px;
    transition: all 0.3s;
  }
  
  .social-link:hover {
    color: #409EFF;
    transform: translateY(-2px);
  }
  
  .share-options {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 15px;
    padding: 10px;
  }
  
  .share-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8px;
    padding: 15px;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s;
  }
  
  .share-item:hover {
    background: #f5f7fa;
  }
  
  .share-item i {
    font-size: 24px;
  }
  
  /* 响应式布局 */
  @media screen and (max-width: 768px) {
    .article-container {
      flex-direction: column;
    }
    
    .article-sidebar {
      width: 100%;
    }
    
    .article-header {
      height: 300px;
    }
    
    .header-overlay {
      padding: 20px;
    }
    
    .title {
      font-size: 24px;
    }
    
    .meta-info {
      flex-direction: column;
      gap: 15px;
    }
    
    .article-stats {
      justify-content: flex-start;
    }
  }
  
  /* 添加 mavon-editor 相关样式 */
  .markdown-body {
    min-height: 400px;
  }
  
  /deep/ .v-note-wrapper {
    border: none !important;
    z-index: 1;
  }
  
  /deep/ .v-note-panel {
    border: none !important;
  }
  
  /deep/ .v-show-content {
    background-color: #fff !important;
    padding: 0 !important;
  }

  /* 整体文章容器 */
.article-content {
  max-width: 860px;
  margin: 0 auto;
  padding: 40px 20px;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
  background: var(--bg-white);
  border-radius: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

/* 文章头部 */
.article-header {
  margin-bottom: 48px;
  padding-bottom: 24px;
  border-bottom: 1px solid var(--border-color);
}

.article-header h1 {
  font-size: 2.4em;
  font-weight: 700;
  margin-bottom: 24px;
  color: var(--text-primary);
  line-height: 1.4;
}

/* 文章元信息 */
.article-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
}

.meta-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.author-avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid var(--primary-color);
  padding: 2px;
}

.author-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.author-name {
  font-weight: 600;
  color: var(--text-primary);
}

.publish-time {
  color: var(--text-secondary);
}

.meta-right .meta-item {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  color: var(--text-secondary);
  margin-left: 20px;
}

/* 文章主体内容 */
.article-body {
  font-size: 16px;
  line-height: 1.8;
  color: var(--text-primary);
}

/* 段落样式 */
.article-body p {
  margin: 1.5em 0;
  text-indent: 2em;
  letter-spacing: 0.05em;
}

/* 标题样式 */
.article-body h2 {
  font-size: 1.8em;
  font-weight: 600;
  margin: 2em 0 1em;
  padding-bottom: 0.5em;
  border-bottom: 2px solid var(--primary-light);
  color: var(--text-primary);
}

.article-body h3 {
  font-size: 1.4em;
  font-weight: 600;
  margin: 1.5em 0 1em;
  color: var(--text-primary);
}

/* 列表样式 */
.article-body ul, 
.article-body ol {
  padding-left: 2em;
  margin: 1em 0;
}

.article-body li {
  margin: 0.5em 0;
  line-height: 1.7;
  color: var(--text-primary);
}

/* 图片容器 */
.image-container {
  margin: 2em auto;
  text-align: center;
}

.image-container img {
  max-width: 100%;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.image-container img:hover {
  transform: scale(1.02);
}

/* 代码块样式 */
.article-body pre {
  background: var(--code-bg);
  border-radius: 12px;
  padding: 20px;
  margin: 1.5em 0;
  overflow-x: auto;
  font-family: 'Fira Code', monospace;
  font-size: 0.9em;
  line-height: 1.6;
  border: 1px solid var(--border-color);
}

.article-body code {
  font-family: 'Fira Code', monospace;
  padding: 2px 6px;
  background: var(--code-bg);
  border-radius: 4px;
  font-size: 0.9em;
  color: var(--primary-color);
}

/* 引用块样式 */
.article-body blockquote {
  margin: 2em 0;
  padding: 1em 1.5em;
  border-left: 4px solid var(--primary-color);
  background: var(--primary-light);
  border-radius: 0 8px 8px 0;
  color: var(--text-primary);
}

.article-body blockquote p {
  margin: 0;
  text-indent: 0;
}

/* 表格样式 */
.article-body table {
  width: 100%;
  margin: 2em 0;
  border-collapse: collapse;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.article-body th,
.article-body td {
  padding: 12px 16px;
  border: 1px solid var(--border-color);
  text-align: left;
}

.article-body th {
  background: var(--primary-light);
  font-weight: 600;
  color: var(--primary-color);
}

/* 暗色模式适配 */
.dark-mode .article-content {
  background: var(--bg-dark-secondary);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.2);
}

.dark-mode .article-body h2 {
  border-bottom-color: var(--primary-dark);
}

.dark-mode .article-body blockquote {
  background: var(--primary-dark);
}

.dark-mode .article-body pre {
  background: var(--bg-dark);
  border-color: var(--border-dark);
}

.dark-mode .article-body code {
  background: var(--bg-dark);
}

.dark-mode .article-body table {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.dark-mode .article-body th {
  background: var(--primary-dark);
}

/* 响应式适配 */
@media (max-width: 768px) {
  .article-content {
    padding: 20px 16px;
  }

  .article-header h1 {
    font-size: 1.8em;
  }

  .meta-right {
    display: none;
  }

  .article-body h2 {
    font-size: 1.5em;
  }

  .article-body h3 {
    font-size: 1.3em;
  }
}
  </style>